package com.adjaisd.scarecrow.common.utils.mqtt;

import com.adjaisd.scarecrow.entity.Device;
import com.adjaisd.scarecrow.entity.DeviceGps;
import com.adjaisd.scarecrow.entity.DeviceStatus;
import com.adjaisd.scarecrow.entity.Quota;
import com.adjaisd.scarecrow.service.DeviceGpsService;
import com.adjaisd.scarecrow.service.DeviceService;
import com.adjaisd.scarecrow.service.DeviceStatusService;
import com.adjaisd.scarecrow.service.QuotaService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class Monitor {

    @Autowired
    private EmqClient emqClient;

    @Autowired
    DeviceService deviceService;

    @Autowired
    QuotaService quotaService;

    @Autowired
    DeviceStatusService deviceStatusService;

    @Autowired
    private DeviceGpsService deviceGpsService;

    @PostConstruct
    public void init() throws MqttException {
        emqClient.connect();
        System.out.println("初始化方法，订阅主题");
        // 查询所有存在且开启的设备
        QueryWrapper<DeviceStatus> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(DeviceStatus::getStatus, true);
        List<DeviceStatus> list = deviceStatusService.list(wrapper);
        List<Long> deviceIdList = list.stream().map(DeviceStatus::getId).collect(Collectors.toList());
        QueryWrapper<Device> wrapper1 = new QueryWrapper<>();
        wrapper1.lambda().gt(Device::getBindTime, 0L)
                .in(Device::getId, deviceIdList);
        List<Device> deviceList = deviceService.list(wrapper1);
        List<Long> numberList = deviceList.stream().map(Device::getNumber).collect(Collectors.toList());

        // 找到所有有效订阅的指标
        QueryWrapper<Quota> wrapper2 = new QueryWrapper<>();
        wrapper2.lambda().gt(Quota::getCreateTime, 0L)
                .in(Quota::getNumber, numberList);
        List<Quota> quotaList = quotaService.list(wrapper2);
        HashSet<Quota> quotas = Sets.newHashSet(quotaList);
        for (Quota quota : quotas) {
            emqClient.subscribe("$queue/" + quota.getSubject());
            // emqClient.subscribe("$queue/" + "device-gps");
        }
        emqClient.subscribe("$queue/" + "device/gps");
    }

}
